package com.myopen.controller.admin;

import com.jfinal.core.ActionKey;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.base.BaseController;
import com.myopen.base.BaseVo;
import com.myopen.config.ConstConfig;
import com.myopen.model.User;
import com.myopen.util.ValidateKit;

public class AdminController extends BaseController{

	@ActionKey("/admin")
	public void admin_index(){
		renderTemplate("/admin/index.html");
	}
	
	@ActionKey("/admin/login")
	public void admin_login(){
		getSession().invalidate();//跳转登录之前清空一下Session信息
		renderCaptcha();
		renderTemplate("/admin/login.html");
	}
	
	@ActionKey("/admin/login/action")
	public void admin_login_action(){
		
		BaseVo baseVo=new BaseVo();
		
		String loginName=getPara("loginName");
		String password=getPara("password");
		if(!validateCaptcha("captchaCode")) {
			baseVo.setCode("3");//验证码错误
			renderJson(baseVo);
			return;
		}
		
		Record user=null;
		if(ValidateKit.isEmail(loginName)){
			user=User.dao.getRecordByEmail(loginName);
		}else if(ValidateKit.isPhone(loginName)) {
			user=User.dao.getRecordByCellphone(loginName);
		}else {
			user=User.dao.getRecordByUsername(loginName);
		}
		
		if(user!=null){
			password=User.encryptPassword(password, user.getStr("salt"));
			if(password.equals(user.getStr("password"))){
				//此处设置用户session，当跳转到首页的时候会自动获取角色权限等信息
				setSessionAttr(ConstConfig.SESSION_ADMIN_USER, user);
			}else{
				baseVo.setCode("1");//密码错误
			}
		}else{
			baseVo.setCode("2");//登录名不存在
		}
		
		renderJson(baseVo);
		
	}
	
	@ActionKey("/admin/loginout")
	public void admin_loginout(){
		getSession().invalidate();
		redirect("/admin/login");
		
	}
	
	
}
